﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NoSqlTest.EfContext
{
    public class DbContextFactory : IDbContextFactory
    {
        private readonly EfDbContext _Context = new EfDbContext();
        private static int _iSeed = 0;
        private readonly DBConnectionOption _readAndWrite = null;
        public DbContextFactory(IOptionsMonitor<DBConnectionOption> options)
        {
            _readAndWrite = options.CurrentValue;
        }
        public EfDbContext ConnWriteOrRead(WriteAndReadEnum writeAndRead)
        {
            //判断枚举，不同的枚举可以创建不同的Context 或者更换Context链接；
            switch (writeAndRead)
            {
                case WriteAndReadEnum.Write:
                    ToWrite();
                    break;  //选择链接//更换_Context链接   //选择链接
                case WriteAndReadEnum.Read:
                    ToRead();
                    break;  //选择链接//更换_Context链接
                default:
                    break;
            }
            return _Context;
        }
        /// <summary>
        /// 更换成主库连接
        /// </summary>
        /// <returns></returns>
        private void ToWrite()
        {
            string conn = _readAndWrite.WriteConnection;
            _Context.ToWriteOrRead(conn);
        }
        /// <summary>
        /// 更换成主库连接
        /// 
        /// ///策略---数据库查询的负载均衡
        /// </summary>
        /// <returns></returns>
        private void ToRead()
        {
            var conn = this._readAndWrite.ReadConnectionList[_iSeed++ % this._readAndWrite.ReadConnectionList.Count];//轮询; 
            _Context.ToWriteOrRead(conn);
        }
    }
}
